package com.mvc.loadconfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mvc.annotation.ActionAnnotation;
import com.mvc.annotation.FormAnnotation;
import com.mvc.annotation.ResultAnnotestion;
import com.mvc.util.Beans;

public class GetallActionBean implements Loadconfiginfor {
	private Object[] getBeanbyAction(String actionpath) {
		Object[] action = new Object[4];
		try {
			Class<?> actionclass = Class.forName(actionpath);
			if (actionclass.isAnnotationPresent(ActionAnnotation.class)) {
				ActionAnnotation aa = (ActionAnnotation) actionclass
						.getAnnotation(ActionAnnotation.class);
				action[0] = aa.path();
				action[1] = aa.name();
				action[2] = actionclass.getName();
				ResultAnnotestion[] results = aa.result();
				Map<String, String> resultmap = new HashMap<String, String>();
				for (ResultAnnotestion result : results) {
					resultmap.put(result.name(), result.path());
				}
				action[3] = resultmap;
			} else {
				action = null;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			action = null;
		}
		return action;
	}

	private String[] getBeanByForm(String formpath) {

		String[] form = new String[2];
		try {
			Class<?> formclass = Class.forName(formpath);
			if (formclass.isAnnotationPresent(FormAnnotation.class)) {
				FormAnnotation fa = (FormAnnotation) formclass
						.getAnnotation(FormAnnotation.class);
				form[0] = fa.name();
				form[1] = formclass.getName();
			} else {
				form = null;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			form = null;
		}
		return form;
	}

	@Override
	public Map<String, Beans> getConfigMap(String path) {
		GetallActionBean gab = new GetallActionBean();
		Map<String, Beans> configmap = new HashMap<String, Beans>();

		GetBeanpath gbp = new GetBeanpath(path);
		List<String> actionpaths = gbp.getActionpathlist();
		List<String> formpaths = gbp.getFormpathlist();

		Map<String, String> formmap = new HashMap<String, String>();
		for (String formpath : formpaths) {
			String[] formstring = gab.getBeanByForm(formpath);
			if (formstring != null)
				formmap.put(formstring[0], formstring[1]);
		}
		for (String actionpath : actionpaths) {
			Object[] action = getBeanbyAction(actionpath);
			if (action != null) {
				Beans xb = new Beans();
				xb.setActiontype(action[2].toString());
				xb.setName(action[1].toString());
				xb.setPath(action[0].toString());
				xb.setFormtype(formmap.get(action[1]));
				xb.setResult((Map) action[3]);
				configmap.put(action[0].toString(), xb);
			}
		}

		return configmap;
	}

	public static void main(String[] args) {
		String path = "E:\\tomcat2\\webapps\\mvc4\\WEB-INF\\classes\\";
		GetallActionBean gab = new GetallActionBean();
		gab.getConfigMap(path);
	}
}
